package Communication;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;



import Protocolo.MiniTCP;

public class Servidor {
	private static MiniTCP serverSocket;
	private static ExecutorService pool;

	public Servidor(int port, int poolSize) throws IOException {
		serverSocket = new MiniTCP(port);
		pool = Executors.newFixedThreadPool(poolSize);
	}

	public void serve() throws SocketException {
		try {
			while (true) {
				pool.execute(new Handler(serverSocket.acceptConnection()));
			}
		} catch (Exception e) {
			pool.shutdown();
			e.printStackTrace();
		}
	}

	boolean calc;
	int lastRead;
	int read;

	class calculateTime extends TimerTask {
		public void run() {
			System.out.println((double)(read - lastRead)/1048576 + " MB/sec (bytes read: " + read + ")");
			calc = false;
		}
	}

	class Handler implements Runnable {
		private MiniTCP socket;
		Handler(MiniTCP socket) {
			this.socket = socket;
		}
		public void run() {
			calc = false;
			read = 0;
			Timer lo = new Timer();
			try {
				socket.start();
				FileOutputStream fout = new FileOutputStream(new File("C:\\Users\\gsa2\\Desktop\\Transf\\American Idol.mp4"));
				while (true) {
					if (socket.getInputStream().available() > 0) {
						byte[] lol = new byte[socket.getInputStream().available()];
						read += socket.getInputStream().read(lol);
						if (!calc) {
							calc = true;
							lastRead = read;
							lo.schedule(new calculateTime(), 1000);
						}
						fout.write(lol);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}